import axios from "axios";
import { ElMessage, tourContentEmits } from "element-plus";

export const _axios = axios.create({
    baseURL: 'http://localhost:8080', // 设置基地址
});




export const request = (url, method, params, callback) => {
    // 封装数据
    const axiosConfig = {
        url,
        method
    }
    // 如果是post请求则转化为 FormData格式
    if (method == 'post') {
        const formData = new FormData()
        for(let key in params) {
            formData.append(key, params[key])
        }
        //如果没有这个属性 就创建然后赋值
        axiosConfig.data = formData
    }else{
        axiosConfig.params = params
    }
   
    // 发送请求

    _axios.request(axiosConfig).then(response => {

        //如果请求成功
        if(response.data.code === 200) {
            // message 有内容
            if(response.data.message) {
                ElMessage.success(response.data.message)
            }
            //回调函数内容
            callback(response.data.content)
        }else {//请求失败 提示失败信息
            ElMessage.error(response.data.message)
        }
    }).catch(error => {
        console.dir(error)
    }).finally(() => {
        
    })
}

//进一步封装get和post请求
export const get = (url, params, callback) => {
    request(url, 'get', params, callback)
}
export const post = (url, params, callback, formObj = null) => {
    if(formObj) {// 是否有表单验证
        formObj.value.validate(valid => {
            if(valid) {//如果校验通过 发请求
                request(url, 'post', params, callback)
            }
        })
    }else{
        request(url, 'post', params, callback)
    }
}